package com.shopx.base.service.impl;


import com.shopx.base.bean.SysSeq;
import com.shopx.base.constants.ResultCodeEnum;
import com.shopx.base.dao.db1.SysSeqDao;
import com.shopx.base.exception.ShopxException;
import com.shopx.base.model.SysSeqModel;
import com.shopx.base.service.ISysSeqService;
import com.shopx.cmm.DTO.PageDTO;
import com.shopx.core.common.RedisKeyConstant;
import com.shopx.core.utils.DateTimeUtil;
import com.shopx.core.utils.StringUtil;
import com.shopx.dal.redis.CacheServiceFactory;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class SysSeqServiceImpl implements ISysSeqService {

  @Override
  public String getTabSeq(String tabName, Integer length,String prefix) throws ShopxException {
    if (StringUtil.isEmpty(tabName)) {
      throw new ShopxException(ResultCodeEnum.PAR_NULL);
    }
    String curDt = DateTimeUtil.getDate8();
    SysSeq sysSeq = (SysSeq) CacheServiceFactory.getCacheService().get(RedisKeyConstant.tabSeqPre+tabName);
    if(sysSeq==null){
      //不存在，则新增
      sysSeq = new SysSeq();
      sysSeq.setCurDt(curDt);
      sysSeq.setSeqId(1L);
      sysSeq.setUpdateTime(DateTimeUtil.getDateTime14());
      CacheServiceFactory.getCacheService().set(RedisKeyConstant.tabSeqPre+tabName,sysSeq);
      return packingSeq(String.valueOf(1L), length,prefix);
    }
    sysSeq.setUpdateTime(DateTimeUtil.getDateTime14());
    //存在，判断是否是新的一天
    if(curDt.compareTo(sysSeq.getCurDt())>0){
      //新的一天
      sysSeq.setSeqId(1L);
      sysSeq.setCurDt(curDt);
      CacheServiceFactory.getCacheService().set(RedisKeyConstant.tabSeqPre+tabName,sysSeq);
      return packingSeq(String.valueOf(1L), length,prefix);
    }else{
      //当天
      long seqId = sysSeq.getSeqId()+1;
      sysSeq.setSeqId(seqId);
      CacheServiceFactory.getCacheService().set(RedisKeyConstant.tabSeqPre+tabName,sysSeq);
      return packingSeq(String.valueOf(seqId), length,prefix);
    }
  }

  private String packingSeq(String seq, Integer length,String prefix) {
    if (length == null || length <= 0) {
      length = 6;
    }
    StringBuilder sb = new StringBuilder(DateTimeUtil.getDate8().substring(2,8));
    seq = createRandomNum() + StringUtils.leftPad(seq + "", length, "0");
    //左边不足位补0
    sb.append(seq);
    if(!StringUtil.isEmpty(prefix)){
      //存在前缀
      return prefix+sb.toString();
    }
    return sb.toString();
  }

  /**
   * @descript 生成四位随机数
   *
   * @author lituo
   * @date 2021/12/22 9:26
   * @return int
   */
  private int createRandomNum() {
    int num = (int) ((Math.random() * 9 + 1) * 1000);
    return num;
  }
}

